package com.uobgroup.ews.uam.core.dao;

import java.util.List;

import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.uobgroup.ews.uam.core.domain.SecurityGroup;

@Repository
public class SecurityGroupDaoImpl extends AbstractJpaDao<SecurityGroup> implements SecurityGroupDao {

   public SecurityGroupDaoImpl() {
      this.setClazz(SecurityGroup.class);
   }

   @Override
   public long count() {
      long count = entityManager.createQuery("SELECT COUNT(o) FROM SecurityGroup o", Long.class).getSingleResult();
      return count;
   }

   @Override
   public List<SecurityGroup> findAll(int firstResult, int maxResults) {
      List<SecurityGroup> securityGroups = entityManager
            .createQuery("SELECT o FROM SecurityGroup o", SecurityGroup.class).setFirstResult(firstResult)
            .setMaxResults(maxResults).getResultList();
      return securityGroups;
   }

   @SuppressWarnings("unchecked")
   public SecurityGroup findName(String roleName) {
      Query query = entityManager.createQuery("SELECT o FROM SecurityGroup o where lower(o.displayName) = :roleName",
            SecurityGroup.class);
      query.setParameter("roleName", roleName.toLowerCase());
      List<SecurityGroup> securityGroups = query.getResultList();
      if (securityGroups.isEmpty())
         return null;
      SecurityGroup securityGroup = securityGroups.get(0);
      return securityGroup;
   }

   @SuppressWarnings("unchecked")
   @Override
   public List<SecurityGroup> findAllSecurityGroupsThatHasNoSegment() {
      Query query = entityManager.createNamedQuery(SecurityGroup.QUERY_FIND_SECURITYGROUPS_THAT_HAS_NO_SEGMENT);
      List<SecurityGroup> results = (List<SecurityGroup>) query.getResultList();
      return results;
   }
}
